
package com.xiaoh.compare.utils;

import com.xiaoh.compare.bo.CompareMo;
import difflib.DiffRow;
import difflib.DiffRowGenerator;
import net.htmlparser.jericho.Source;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


//被注释的地方先不要删，可能会有用！
public class CompareFiles {
//	变化的结果（tag）
	public static final String Result_EQUAL = "EQUAL";
	public static final String Result_INSERT = "INSERT";
	public static final String Result_DELETE = "DELETE";
	public static final String Result_CHANGE = "CHANGE";
	/***
	 * 读文件
	 * @param filename
	 * @return
	 */
	private static List<String> fileToLines(String filename) {
		List<String> lines = new LinkedList<String>();
		String line = "";
		try {
		  //编译环境为GBK的情况
	         BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "GBK"));          
//			BufferedReader in = new BufferedReader(new FileReader(filename));
			while ((line = in.readLine()) != null) {
				lines.add(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lines;
	}
	
	/***
	 * 对文件进行比较
	 * INSERT, DELETE, CHANGE, EQUAL
	 * @param fromFileName 原来的文件名
	 * @param toFileName 新的文件名
	 */
	public static List<CompareMo> compareAll(String fromFileName, String toFileName) {
		List<String> original = fileToLines(fromFileName);
		List<String> revised = fileToLines(toFileName);

		final DiffRowGenerator.Builder builder = new DiffRowGenerator.Builder();
		final DiffRowGenerator dfg = builder.build();
		final List<DiffRow> rows = dfg.generateDiffRows(original, revised);
		List<CompareMo> listCompareMo = new ArrayList<CompareMo>();
		int i=1;
		int oldSize = original.size();
		int newSize = revised.size();
		int insertSize = 0;
		int deleteSize = 0;
		for (final DiffRow diffRow : rows) {
			String tag = diffRow.getTag().toString();
			String oldLine = diffRow.getOldLine();
			String newLine = diffRow.getNewLine();
											
			
			if(Result_CHANGE.equals(tag)){
				boolean isInset = false;
				if ((i-insertSize) <= oldSize) {
					if(oldLine!=null&& oldLine.trim().length()==0){
						if(!original.get(i-1-insertSize).equals(oldLine)){
							tag = Result_INSERT;
							isInset = true;
							insertSize ++;
						}
					}
				}
				if (!isInset) {
					if ((i-deleteSize) <= newSize) {
						if(newLine!=null&& newLine.trim().length()==0){
							if(!revised.get(i-1-deleteSize).equals(oldLine)){
								tag = Result_DELETE;
								isInset = true;
								deleteSize ++;
							}
						}
					}
				}
			}
	//i表示行号				
//			listCompareMo.add(new CompareMo(
//					i, oldLine, 
//					newLine, 
//					tag
//			));
//			i++;
			listCompareMo.add(new CompareMo(
					 oldLine, 
					newLine, 
					tag
			));						
		}
		return listCompareMo;
	}
	
	
	
//	去除html的所有标签，如<br>换行符等标签
	public static String getPlainTextWithoutHtmlTag(String  content) {
        if(content == null || "".equals(content)){
            return "";
        }else{
            Source src = new Source(content);
            String str = src.getTextExtractor().toString().trim();
            return str.replaceAll(" ","").replaceAll("　　", "");
        }
    }

	//文件比较方法
	public static String getcompareFiles(String  anew,String  bnew,String  cnew) throws IOException {
		
		String a="";
		String contentWord="";
		int count=0;
		String b2="";
		String b3="";
		//doc形式
//		 anew="C:\\compareText\\originalFile.doc";
//		 bnew="C:\\compareText\\newFile.doc";
//		 cnew="C:\\compareText\\newFile2.doc";
	
				
//比较差异
		List<CompareMo> compares = CompareFiles.compareAll(
				//txt形式
//				"C:\\compareText\\originalFile.txt",
//				"C:\\compareText\\newFile.txt");
				
				//doc形式				
//				"C:\\compareText\\originalFile.doc",
//				"C:\\compareText\\newFile.doc");
				anew,bnew);
				
				

		for (CompareMo compare : compares) {
//			System.out.println("66"+compare.getId() + " 结果 :" + compare.getType()
//					+ ":" + compare.getOldText() + "<>" + compare.getNewText());
			
			if(compare.getType()=="CHANGE") {	
				 a=compare.getNewText();				
				 contentWord=	getPlainTextWithoutHtmlTag(a);
			System.out.println(contentWord);
			
			
			
//			File doc=new File("C:\\compareText\\newFile3.doc");
//			if(!doc.exists()){
//				doc.createNewFile();
//			}
//			byte bytes[]=new byte[512];
//			bytes=contentWord.getBytes(); 
//			int b=contentWord.length(); 	         
//			FileOutputStream fos=new FileOutputStream(doc);
//			fos.write(bytes,0,b);
//			fos.close();
			
						
//	计算有差异的行数		
			count=++count;
			}			
		}
		
		
			
//				File doc=new File("C:\\compareText\\newFile3.doc");
//				System.out.println("666"+contentWord);
//				if(!doc.exists()){
//					doc.createNewFile();
//				}
//				byte bytes[]=new byte[512];
//				bytes=contentWord.getBytes(); 
//				int b=contentWord.length(); 		         
//				FileOutputStream fos=new FileOutputStream(doc);
//				fos.write(bytes,0,b);
//				fos.close();
		
		//比较差异
		
		List<CompareMo> compares2 = CompareFiles.compareAll(
				//txt形式
//				"C:\\compareText\\newFile.txt",
//				"C:\\compareText\\newFile2.txt");
				
				//doc形式		
//				"C:\\compareText\\newFile.doc",
//	         	"C:\\compareText\\newFile2.doc");
				
				bnew,cnew);

		for (CompareMo compare : compares2) {
//			System.out.println("555"+compare.getId() + " 结果 :" + compare.getType()
//					+ ":" + compare.getOldText() + "<>" + compare.getNewText());
			
//			if(compare.getType()!="DELETE"&&compare.getType()!="CHANGE") {
//			if(compare.getType()=="CHANGE") {
			if(compare.getType()=="INSERT"||compare.getType()=="EQUAL"&&count<2) {

//				System.out.println( "最新版本（拼接完成）"+a);				
				 b2=getPlainTextWithoutHtmlTag(compare.getNewText());	
			    System.out.println(b2);

			}
					
			else	if(compare.getType()=="CHANGE"&&count==0) {
//				System.out.println( "最新版本（拼接完成）"+a);
				
				 b3=getPlainTextWithoutHtmlTag(compare.getOldText());
				 b2=getPlainTextWithoutHtmlTag(compare.getNewText());
			     System.out.println(b3);
			     System.out.println(b2);
			}			
		}
		//判断应该返回哪个值
		if(b3!=null) {
			
			return contentWord+"\n"+b3+"\n"+b2;	
			
			}else {
				return contentWord+"\n"+b2;		
			}
	
		
	}
}

